package com.laowang.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.laowang.common.utils.DateUtils;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.SensitiveInfoUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.redis.RedisCache;
import com.laowang.project.system.domain.UserPointLog;
import com.laowang.project.system.domain.WxUser;
import com.laowang.project.system.domain.vo.LookObj;
import com.laowang.project.system.service.UserPointLogService;
import com.laowang.project.system.service.WxUserService;
import com.laowang.project.websocket.TbMessage;
import com.laowang.project.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.MyTemplateMessage;
import com.laowang.project.system.service.MyTemplateMessageService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

import javax.validation.constraints.NotNull;

/**
 * 用户消息Controller
 *
 * @author laowang
 * @date 2023-05-24
 */
@Api(tags = "用户消息接口")
@RestController
@RequestMapping("/message")
public class MyTemplateMessageController extends BaseController {
    @Autowired
    private MyTemplateMessageService myTemplateMessageService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserPointLogService userPointLogService;

    @ApiOperation(value = "小程序端 发送消息",notes = "")
    @PostMapping("/web/add")
    public AjaxResult webAdd(@Validated @RequestBody MyTemplateMessage myTemplateMessage) {
        String type = myTemplateMessage.getType();//1 发送 2回复
        Integer needPoint = myTemplateMessage.getNeedPoint();

        if (StringUtils.isEmpty(type)){
            return AjaxResult.error("消息类型不能为空");
        }
        if (!type.equals("1") && !type.equals("2")){
            return AjaxResult.error("消息类型不匹配");
        }

        if (type.equals("1")){
            if (needPoint == null){
                return AjaxResult.error("是否需要积分不能为空");
            }
            if (!needPoint.equals(0) && !needPoint.equals(1)){
                return AjaxResult.error("需要积分不匹配");
            }
        }


        @NotNull(message = "发送人不能为空") Integer formId = myTemplateMessage.getFormId();
        @NotNull(message = "接收人不能为空") Integer toUser = myTemplateMessage.getToUser();

        WxUser wxUser = wxUserService.selectWxUserById(formId);
        WxUser wxUser1 = wxUserService.selectWxUserById(toUser);
        //发送
        if (type.equals("1")){
            if (needPoint == 0){
                Integer n = 0;
                if (wxUser.getVipLevel() != null && wxUser.getExpireTime().after(new Date())){
                    n =  wxUser.getVipLevel();
                }

                if ( n == 0 ){
                    //没有会员的           没有副牌每天看一次
                    LookObj lookObj = redisCache.getCacheObject("lookn:" + formId);
                    if (Objects.isNull(lookObj)){
                        lookObj= new LookObj(new Date(), 1);
                        redisCache.setCacheObject("lookn:"+formId,lookObj,2, TimeUnit.DAYS);

                    }else {
                        Date date = lookObj.getDate();
                        if (DateUtils.isSameDay(new Date(),date)){
                            return AjaxResult.success("非会员每天只能打招呼一次,是否需要积分查看");
                        }else {
                            lookObj= new LookObj(new Date(), 1);
                            redisCache.setCacheObject("lookn:"+formId,lookObj,2, TimeUnit.DAYS);
                        }
                    }
                }
                if (n != 0){

                    LookObj lookObj = redisCache.getCacheObject("lookn:" + formId);
                    if (Objects.isNull(lookObj)){
                        lookObj= new LookObj(new Date(), 1);
                        redisCache.setCacheObject("lookn:"+formId,lookObj,2, TimeUnit.DAYS);

                    }else {
                        Date date = lookObj.getDate();
                        if (DateUtils.isSameDay(new Date(),date)){
                            Integer num = lookObj.getNum();
                            if (n == 1){
                                // 一级会员 普通会员每天5次免费打招呼和20次查看，
                                if (num >= 5){
                                    return AjaxResult.success("名车会员每天只能免费5次打招呼,是否需要花费积分");
                                }
                                num++;
                                LookObj  lookObj1 = new LookObj(new Date(), num);
                                redisCache.setCacheObject("lookn:"+formId,lookObj1,2, TimeUnit.DAYS);
                            }else if (n ==2){
                                //银牌会员每天10次打招呼和50次查看
                                if (num >= 10){
                                    return AjaxResult.success("银牌会员每天只能免费10次打招呼,是否需要花费积分");
                                }
                                num++;
                                LookObj  lookObj1 = new LookObj(new Date(), num);
                                redisCache.setCacheObject("lookn:"+formId,lookObj1,2, TimeUnit.DAYS);
                            }else if (n == 3){
                                //金牌会员面体20次免费打招呼和100次查看
                                if (num >= 20){
                                    return AjaxResult.success("金牌会员每天只能免费20次打招呼,是否需要花费积分");
                                }
                                num++;
                                LookObj  lookObj1 = new LookObj(new Date(), num);
                                redisCache.setCacheObject("lookn:"+formId,lookObj1,2, TimeUnit.DAYS);
                            }
                            // 其他的会员就不限制了

                        }else {
                            lookObj= new LookObj(new Date(), 1);
                            redisCache.setCacheObject("lookn:"+formId,lookObj,2, TimeUnit.DAYS);
                        }
                    }
                }

            }else if (needPoint == 1){
                //用积分查看
                Integer points = wxUser.getPoints();
                if (points >= 500){
                    //会员名额用完的情况或者非会员 100积分查看一次通讯录，500积分打一次招呼
                    Integer  newpoints = points -500;
                    wxUser.setPoints(newpoints);
                    wxUserService.updateWxUser( wxUser);

                    //积分日志
                    UserPointLog userPointLog = new UserPointLog();
                    userPointLog.setRemark("积分打招呼");
                    userPointLog.setOldPoint(points);
                    userPointLog.setChangePoint(-500);
                    userPointLog.setNewPoint(newpoints);
                    userPointLog.setUserId(formId);
                    userPointLog.setType(7);//积分打招呼
                    userPointLog.setCreated(new Date());
                    userPointLogService.insertUserPointLog(userPointLog);
                }else {
                    return AjaxResult.success("积分不足500");

                }
            }

        }else if (type.equals("2")){
            //回复
        }

        myTemplateMessageService.insertMyTemplateMessage(myTemplateMessage);

        String content = SensitiveInfoUtils.chineseName(wxUser.getNickname())+" 跟 " +SensitiveInfoUtils.chineseName(wxUser1.getNickname()) +" 打了个招呼!";
        TbMessage tbMessage = new TbMessage();
        tbMessage.setContent(content);
        tbMessage.setCreateTime(new Date());
        tbMessage.setType(1);//全局
        WebSocketServer.sendAll(tbMessage);

        return AjaxResult.success("操作成功","dasda");
    }

    @ApiOperation(value = "小程序端 接收自己的消息",notes = "")
    @GetMapping("/web/getMessage")
    public AjaxResult getMessage() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        MyTemplateMessage myTemplateMessage =new MyTemplateMessage();
        myTemplateMessage.setToUser(mid);
        myTemplateMessage.setStatus(0);//未读
        List<MyTemplateMessage> myTemplateMessages = myTemplateMessageService.selectMyTemplateMessageListWeb(myTemplateMessage);
        return AjaxResult.success("操作成功",myTemplateMessages);
    }


    @ApiOperation(value = "小程序端 读取消息",notes = "")
    @GetMapping("/web/readMsg/{ids}")
    public AjaxResult readMsg(@PathVariable("ids") Integer[] ids) {
        for (Integer id : ids) {
            MyTemplateMessage myTemplateMessage = myTemplateMessageService.selectMyTemplateMessageById(id);
            if (myTemplateMessage !=null){
                myTemplateMessage.setStatus(1);
                myTemplateMessageService.updateMyTemplateMessage(myTemplateMessage);
            }else {
                return AjaxResult.error("消息为空");
            }
        }

        return AjaxResult.success("操作成功");
    }

    /**
     * 查询用户消息列表
     */
    @ApiOperation(value = "查询用户消息列表",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:list')")
    @GetMapping("/list")
        public TableDataInfo list(MyTemplateMessage myTemplateMessage) {
        startPage();
        List<MyTemplateMessage> list = myTemplateMessageService.selectMyTemplateMessageList(myTemplateMessage);
        return getDataTable(list);
    }

    /**
     * 导出用户消息列表
     */
    @ApiOperation(value = "导出用户消息列表",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:export')")
    @Log(title = "用户消息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyTemplateMessage myTemplateMessage) {
        List<MyTemplateMessage> list = myTemplateMessageService.selectMyTemplateMessageList(myTemplateMessage);
        ExcelUtil<MyTemplateMessage> util = new ExcelUtil<MyTemplateMessage>(MyTemplateMessage.class);
        return util.exportExcel(list, "message");
    }

    /**
     * 获取用户消息详细信息
     */
    @ApiOperation(value = "获取用户消息详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myTemplateMessageService.selectMyTemplateMessageById(id));
    }

    /**
     * 新增用户消息
     */
    @ApiOperation(value = "新增用户消息",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:add')")
    @Log(title = "用户消息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyTemplateMessage myTemplateMessage) {
        return toAjax(myTemplateMessageService.insertMyTemplateMessage(myTemplateMessage));
    }

    /**
     * 修改用户消息
     */
    @ApiOperation(value = "修改用户消息",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:edit')")
    @Log(title = "用户消息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyTemplateMessage myTemplateMessage) {
        return toAjax(myTemplateMessageService.updateMyTemplateMessage(myTemplateMessage));
    }

    /**
     * 删除用户消息
     */
    @ApiOperation(value = "删除用户消息",notes = "")
    @PreAuthorize("@ss.hasPermi('system:message:remove')")
    @Log(title = "用户消息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myTemplateMessageService.deleteMyTemplateMessageByIds(ids));
    }
}
